"""
Compliance Template API 路由
提供合规模板表的HTTP接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional, List
from uuid import UUID

from db.session import get_db
from schemas.complianceTemplate import (
    ComplianceTemplateCreate,
    ComplianceTemplateUpdate,
    ComplianceTemplateResponse,
    ComplianceTemplateDetailResponse,
    ComplianceTemplatePagination,
    TemplateItemCreate,
    TemplateItemResponse
)
from core import complianceTemplate as compliance_template_service
from log import log_error

router = APIRouter(
    prefix="/compliance-templates",
    tags=["compliance-templates"],
    responses={404: {"description": "Compliance template not found"}},
)

@router.get("/", response_model=ComplianceTemplatePagination)
async def get_compliance_templates(
    name: Optional[str] = None,
    assessment_type: Optional[str] = None,
    version: Optional[str] = None,
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db)
) -> ComplianceTemplatePagination:
    """
    获取合规模板列表，支持分页和过滤。
    
    Args:
        name: 按名称过滤（可选）
        assessment_type: 按评估类型过滤（可选）
        version: 按版本号过滤（可选）
        skip: 跳过的记录数
        limit: 返回的最大记录数
        db: 数据库会话依赖
        
    Returns:
        分页合规模板列表
    """
    try:
        # 构建过滤条件
        filters = {}
        if name:
            filters["name"] = name
        if assessment_type:
            filters["assessment_type"] = assessment_type
        if version:
            filters["version"] = version
        
        templates = await compliance_template_service.get_compliance_templates(
            db, skip, limit, filters if filters else None
        )
        return templates
    except Exception as e:
        log_error(f"Error getting compliance templates: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve compliance templates: {str(e)}"
        )

@router.get("/{template_id}", response_model=ComplianceTemplateDetailResponse)
async def get_compliance_template(
    template_id: UUID,
    include_items: bool = True,
    db: AsyncSession = Depends(get_db)
) -> ComplianceTemplateDetailResponse:
    """
    根据ID获取特定合规模板，包括其模板项。
    
    Args:
        template_id: 合规模板ID
        include_items: 是否包含模板项（默认为True）
        db: 数据库会话依赖
        
    Returns:
        合规模板详情
        
    Raises:
        HTTPException: 当合规模板不存在时
    """
    try:
        template = await compliance_template_service.get_compliance_template(db, template_id, include_items)
        if template is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Compliance template with ID {template_id} not found"
            )
        return template
    except HTTPException:
        raise
    except Exception as e:
        log_error(f"Error getting compliance template {template_id}: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve compliance template: {str(e)}"
        )

@router.post("/", response_model=ComplianceTemplateResponse, status_code=status.HTTP_201_CREATED)
async def create_compliance_template(
    template: ComplianceTemplateCreate,
    db: AsyncSession = Depends(get_db)
) -> ComplianceTemplateResponse:
    """
    创建新的合规模板。
    
    Args:
        template: 合规模板数据
        db: 数据库会话依赖
        
    Returns:
        创建的合规模板
        
    Raises:
        HTTPException: 当数据验证失败时
    """
    try:
        created_template = await compliance_template_service.create_compliance_template(db, template)
        return created_template
    except HTTPException as e:
        log_error(f"Validation error creating compliance template: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        log_error(f"Error creating compliance template: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to create compliance template: {str(e)}"
        )

@router.post("/items", response_model=TemplateItemResponse, status_code=status.HTTP_201_CREATED)
async def create_template_item(
    item: TemplateItemCreate,
    db: AsyncSession = Depends(get_db)
) -> TemplateItemResponse:
    """
    为现有模板添加新的模板项。
    
    Args:
        item: 模板项数据
        db: 数据库会话依赖
        
    Returns:
        创建的模板项
        
    Raises:
        HTTPException: 当数据验证失败或模板不存在时
    """
    try:
        created_item = await compliance_template_service.create_template_item(db, item)
        return created_item
    except HTTPException as e:
        log_error(f"Validation error creating template item: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        log_error(f"Error creating template item: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to create template item: {str(e)}"
        )

@router.put("/{template_id}", response_model=ComplianceTemplateResponse)
async def update_compliance_template(
    template_id: UUID,
    template: ComplianceTemplateUpdate,
    db: AsyncSession = Depends(get_db)
) -> ComplianceTemplateResponse:
    """
    更新现有合规模板。
    
    Args:
        template_id: 合规模板ID
        template: 更新的合规模板数据
        db: 数据库会话依赖
        
    Returns:
        更新后的合规模板
        
    Raises:
        HTTPException: 当合规模板不存在或数据验证失败时
    """
    try:
        updated_template = await compliance_template_service.update_compliance_template(db, template_id, template)
        if updated_template is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Compliance template with ID {template_id} not found"
            )
        return updated_template
    except HTTPException as e:
        log_error(f"Validation error updating compliance template {template_id}: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        log_error(f"Error updating compliance template {template_id}: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to update compliance template: {str(e)}"
        )

@router.delete("/{template_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_compliance_template(
    template_id: UUID,
    db: AsyncSession = Depends(get_db)
) -> None:
    """
    删除合规模板。
    
    Args:
        template_id: 合规模板ID
        db: 数据库会话依赖
        
    Raises:
        HTTPException: 当合规模板不存在时
    """
    try:
        deleted = await compliance_template_service.delete_compliance_template(db, template_id)
        if not deleted:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Compliance template with ID {template_id} not found"
            )
    except HTTPException:
        raise
    except Exception as e:
        log_error(f"Error deleting compliance template {template_id}: {str(e)}", module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to delete compliance template: {str(e)}"
        )

@router.get("/assessment-plan/{assessment_plan_id}/items", response_model=List[TemplateItemResponse])
async def get_template_items_by_assessment_plan(
    assessment_plan_id: UUID,
    title: Optional[str] = Query(None, description="标题过滤条件（支持模糊匹配）"),
    compliance_type: Optional[str] = Query(None, description="合规类型过滤（risk/guarantee）"),
    maturity_level: Optional[int] = Query(None, description="成熟度等级过滤", ge=1, le=5),
    db: AsyncSession = Depends(get_db)
) -> List[TemplateItemResponse]:
    """
    根据评估计划ID和多种过滤条件获取对应模板的模板项列表。
    
    通过评估计划ID找到关联的模板，然后返回该模板下符合条件的所有模板项。
    主要用于数据安全评估（105）等场景。
    
    Args:
        assessment_plan_id: 评估计划ID
        title: 标题过滤条件（可选，支持模糊匹配）
        compliance_type: 合规类型过滤（可选，risk/guarantee）
        maturity_level: 成熟度等级过滤（可选，1-5）
        db: 数据库会话依赖
        
    Returns:
        模板项列表
        
    Raises:
        HTTPException: 当评估计划不存在或未关联模板时
    """
    try:
        # 构建过滤条件字典
        filters = {}
        if title:
            filters["title"] = title
        if compliance_type:
            filters["compliance_type"] = compliance_type
        if maturity_level:
            filters["maturity_level"] = maturity_level
        
        template_items = await compliance_template_service.get_template_items_by_assessment_plan(
            db, assessment_plan_id, filters if filters else None
        )
        return template_items
    except HTTPException:
        raise
    except Exception as e:
        log_error(f"获取评估计划模板项失败，评估计划ID: {assessment_plan_id}，错误: {str(e)}", 
                 module="routers.complianceTemplate")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取模板项失败: {str(e)}"
        )
